package com.android.equipment.ui.group

import android.os.Bundle
import android.view.View
import android.widget.AdapterView.OnItemLongClickListener
import com.android.equipment.R
import com.android.equipment.adapter.PeopleInfoAdapter
import com.android.equipment.base.BaseActivity
import com.android.equipment.bean.TeamGroupDeviceData
import com.android.equipment.bean.TeamGroupRelevanceData
import com.android.equipment.dao.Device
import com.android.equipment.dao.People
import com.android.equipment.dao.TeamGroup
import com.android.equipment.dao.TeamGroupDetail
import com.android.equipment.dao.operate.DaoDevice
import com.android.equipment.dao.operate.DaoPeople
import com.android.equipment.dao.operate.DaoTeamGroup
import com.android.equipment.dao.operate.DaoTeamGroupDetail
import com.android.equipment.databinding.ActivityEditPeopleGroupBinding
import com.android.equipment.ui.dialog.SelectPeopleDialog
import com.android.equipment.ui.dialog.TeamGroupPeopleRelevanceDeviceDialog
import com.android.equipment.utils.ToastUtil
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup

class EditTeamGroupActivity : BaseActivity<ActivityEditPeopleGroupBinding>() {
    private val peopleInfoAdapter: PeopleInfoAdapter by lazy {
        PeopleInfoAdapter(R.layout.item_people_info)
    }
    var id: Long = -1L
    private lateinit var teamGroup: TeamGroup
    private lateinit var deviceList: List<Device>
    private lateinit var peopleList: List<People>

    private lateinit var teamGroupRelevanceDataList: MutableList<TeamGroupRelevanceData> //记录的是班组详情的的临时数据  用来新增班组

    override fun setLayoutContent() = ActivityEditPeopleGroupBinding.inflate(layoutInflater)

    override fun initView(savedInstanceState: Bundle?) {
        id = intent.getLongExtra("id", -1L)

        initRecycler()
    }

    override fun initData() {
        if (id != -1L) {
            binding.tvSubmit.visibility = View.GONE
            teamGroup = DaoTeamGroup.getInstance().getTeamGroup(id)
            teamGroup.let {
                binding.etName.setText(it.groupName)

                val teamGroupDetails =
                    DaoTeamGroupDetail.getInstance().getTeamGroupDetailByGroupId(it.id)
                teamGroupRelevanceDataList =
                    teamGroupDetails.groupBy { it.peopleId }.map { (peopleId, details) ->
                        val firstDetail = details.first()
                        TeamGroupRelevanceData(
                            peopleId = peopleId,
                            peopleName = firstDetail.peopleName,
                            peoplePhone = firstDetail.peoplePhone,
                            peoplePhoto = firstDetail.peoplePhoto,
                            devices = details.map {
                                TeamGroupDeviceData(
                                    deviceId = it.deviceId,
                                    deviceName = it.deviceName,
                                    deviceCode = it.deviceCode
                                )
                            }
                        )
                    }.toMutableList()

                peopleInfoAdapter.setList(teamGroupRelevanceDataList)
            }
        } else {
            teamGroup = TeamGroup()
            teamGroupRelevanceDataList = mutableListOf()
        }
        deviceList = DaoDevice.getInstance().allDevice
        peopleList = DaoPeople.getInstance().allPeople


    }

    private fun initRecycler() {
        binding.rvPeopleInfo.adapter = peopleInfoAdapter

        peopleInfoAdapter.addChildClickViewIds(R.id.tv_change_bind)
        peopleInfoAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.tv_change_bind) {
                val relevanceData = peopleInfoAdapter.data[position]
                val currentDevices = relevanceData.devices.map { it.deviceId }
                val existDeviceIds =
                    peopleInfoAdapter.data.flatMap { it.devices.map { device -> device.deviceId } }
                deviceList.forEach {
                    if (existDeviceIds.contains(it.id)) {
                        it.isOccupy = true
                    }
                    if (currentDevices.contains(it.id)) {
                        it.isOccupy = false
                        it.isSelect = true
                    }
                }

                val people = DaoPeople.getInstance().getPeople(relevanceData.peopleId)
                showDeviceDialog(people, true)
            }
        }

        peopleInfoAdapter.setOnItemLongClickListener { adapter, view, position ->
            XPopup.Builder(mContext).asConfirm("是否删除该成员？", "") {
                if (id != -1L) {
                    DaoTeamGroupDetail.getInstance()
                        .deleteTeamGroupDetailByPeopleId(peopleInfoAdapter.data[position].peopleId)
                }
                peopleInfoAdapter.removeAt(position)
            }.show()
            true
        }
    }

    override fun initEvent() {
        binding.tvContactPeople.setOnClickListener {
            if (peopleList.isEmpty()) {
                ToastUtil.showToastSafe("请先添加人员!")
                return@setOnClickListener
            }


            if (deviceList.isEmpty()) {
                ToastUtil.showToastSafe("请先添加设备!")
                return@setOnClickListener
            }


            XPopup.Builder(mContext)
                .asBottomList(
                    "请选择一项",
                    peopleList.map { "${it.peopleName}(${it.peoplePhone})" }.toTypedArray()
                ) { position, text ->
                    var isHave = false
                    peopleInfoAdapter.data.forEach {
                        if (it.peopleName == peopleList[position].peopleName) {
                            ToastUtils.showShort("该成员已添加")
                            isHave = true
                            return@forEach
                        }
                    }

                    if (!isHave) {
                        val selDevices =
                            peopleInfoAdapter.data.flatMap { it.devices }  //当前所有列表中已经绑定过的设备
                        val ids = selDevices.map { it.deviceId }

                        deviceList.forEach { device ->
                            if (ids.contains(device.id)) {
                                device.isOccupy = true
                            }
                        }
                        //peopleInfoAdapter.addData(0, peopleList[position])
                        showDeviceDialog(peopleList[position])
                    }

                }.show();


        }


        binding.mTitleBar.leftView.setOnClickListener {
            mSwipeBackHelper.backward()
        }

        binding.tvSubmit.setOnClickListener {
            if (binding.etName.text.isEmpty()) {
                ToastUtil.showToastSafe("请输入班组名称")
                return@setOnClickListener
            }

            if (peopleInfoAdapter.data.size == 0) {
                ToastUtil.showToastSafe("请添加班组成员")
                return@setOnClickListener
            }
            teamGroup.groupName = binding.etName.text.toString()


            val groupId = DaoTeamGroup.getInstance().addTeamGroup(teamGroup)
            teamGroupRelevanceDataList.forEach {
                it.devices.forEach { device ->
                    val teamGroupDetail = TeamGroupDetail()
                    teamGroupDetail.groupId = groupId
                    teamGroupDetail.peopleId = it.peopleId
                    teamGroupDetail.peopleName = it.peopleName
                    teamGroupDetail.peoplePhone = it.peoplePhone
                    teamGroupDetail.peoplePhoto = it.peoplePhoto
                    teamGroupDetail.deviceId = device.deviceId
                    teamGroupDetail.deviceName = device.deviceName
                    teamGroupDetail.deviceCode = device.deviceCode
                    DaoTeamGroupDetail.getInstance().addTeamGroupDetail(teamGroupDetail)
                }
            }

//            else {
//                val teamGroupDetailList =
//                    DaoTeamGroupDetail.getInstance().getTeamGroupDetailByGroupId(id)
//
//                teamGroupDetailList.forEach { teamGroupDetail ->
//                    if (!peopleIds.contains(teamGroupDetail.peopleId)){  //说明是新增的
//                        val index = peopleInfoAdapter.data.indexOfFirst { it.peopleId == teamGroupDetail.peopleId }
//                        val teamGroupRelevanceData = peopleInfoAdapter.data[index]
////                        val teamGroupDetail = TeamGroupDetail()
////                        teamGroupDetail.groupId = id
////                        teamGroupDetail.peopleId = teamGroupRelevanceData.peopleId
////                        teamGroupDetail.peopleName = teamGroupRelevanceData.peopleName
////                        teamGroupDetail.peoplePhone = teamGroupRelevanceData.peoplePhone
////                        teamGroupDetail.peoplePhoto = teamGroupRelevanceData.peoplePhoto
////                        teamGroupDetail.deviceId = teamGroupRelevanceData.deviceId
////                        teamGroupDetail.deviceName = teamGroupDetail.deviceName
////                        DaoTeamGroupDetail.getInstance().addTeamGroupDetail(teamGroupDetail)
//                }
//
//            }
//                //DaoTeamGroup.getInstance().updatePeopleGroup(peopleGroup)
//            }
            mSwipeBackHelper.backward()
        }
    }

    private fun showDeviceDialog(people: People, isFromChangeBind: Boolean = false) {
        XPopup.Builder(mContext)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(
                TeamGroupPeopleRelevanceDeviceDialog(
                    this,
                    people,
                    deviceList,
                    object :
                        TeamGroupPeopleRelevanceDeviceDialog.OnConfirmListener {
                        override fun onConfirm(
                            deviceList: List<Device>,
                            teamGroupRelevanceData: TeamGroupRelevanceData
                        ) {
                            this@EditTeamGroupActivity.deviceList = deviceList

                            if (id != -1L) {  //编辑进来的
                                if (isFromChangeBind) {
                                    var teamGroupRelevanceItem: TeamGroupRelevanceData? = null
                                    val peopleId = teamGroupRelevanceData.peopleId
                                    for (data in teamGroupRelevanceDataList) {
                                        if (peopleId == data.peopleId) {
                                            data.devices = teamGroupRelevanceData.devices
                                            teamGroupRelevanceItem = data
                                            break
                                        }
                                    }

                                    DaoTeamGroupDetail.getInstance().deleteTeamGroupDetailByGroupIdAndPeopleId(id, peopleId)
                                    teamGroupRelevanceItem?.devices?.forEach {
                                        val teamGroupDetail = TeamGroupDetail()
                                        teamGroupDetail.groupId = id
                                        teamGroupDetail.peopleId = teamGroupRelevanceItem.peopleId
                                        teamGroupDetail.peopleName = teamGroupRelevanceItem.peopleName
                                        teamGroupDetail.peoplePhone = teamGroupRelevanceItem.peoplePhone
                                        teamGroupDetail.peoplePhoto = teamGroupRelevanceItem.peoplePhoto
                                        teamGroupDetail.deviceId = it.deviceId
                                        teamGroupDetail.deviceName = it.deviceName
                                        teamGroupDetail.deviceCode = it.deviceCode
                                        DaoTeamGroupDetail.getInstance().addTeamGroupDetail(teamGroupDetail)
                                    }

                                } else {

                                    teamGroupRelevanceDataList.add(teamGroupRelevanceData)

                                    teamGroupRelevanceData.devices.forEach { device ->
                                        val teamGroupDetail = TeamGroupDetail()
                                        teamGroupDetail.groupId = id
                                        teamGroupDetail.peopleId = teamGroupRelevanceData.peopleId
                                        teamGroupDetail.peopleName =
                                            teamGroupRelevanceData.peopleName
                                        teamGroupDetail.peoplePhone =
                                            teamGroupRelevanceData.peoplePhone
                                        teamGroupDetail.peoplePhoto =
                                            teamGroupRelevanceData.peoplePhoto
                                        teamGroupDetail.deviceId = device.deviceId
                                        teamGroupDetail.deviceName = device.deviceName
                                        teamGroupDetail.deviceCode = device.deviceCode
                                        DaoTeamGroupDetail.getInstance()
                                            .addTeamGroupDetail(teamGroupDetail)
                                    }
                                }

                                peopleInfoAdapter.setList(teamGroupRelevanceDataList)
                            } else {  //新增进来的
                                if (isFromChangeBind) { //来自绑定
                                    val peopleId = teamGroupRelevanceData.peopleId
                                    for (item in teamGroupRelevanceDataList) {
                                        if (peopleId == item.peopleId) {
                                            item.devices = teamGroupRelevanceData.devices
                                            break
                                        }
                                    }
                                } else {
                                    teamGroupRelevanceDataList.add(teamGroupRelevanceData)
                                }
                                peopleInfoAdapter.setList(teamGroupRelevanceDataList)
                            }


                        }

                    }
                )
            )
            .show()
    }

    override fun setStatusBar() {
        super.setStatusBar()
        ImmersionBar.with(this)
            .fullScreen(true)
            .statusBarColor(R.color.F8F9FA)
            .statusBarDarkFont(true)
            .titleBar(binding.mTitleBar)
            .init()
    }
}